package com.csrcb.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname ReadWriteFile
 * @Description 读写文件
 * @Date 2020/12/17 13:44
 * @Created by gangye
 */
public class ReadWriteFile {
    private static Logger logger = LoggerFactory.getLogger(ReadWriteFile.class);

    /**
     * 将字符串输入到文件中，若文件不存在，创建后输入，若文件存在会将原有的文件删除后再创建然后将内容输入到文件中
     * @param filePath
     * @param content
     */
    public static void writeContent(String filePath,String content){
        File file = new File(filePath);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 将字符串输入到文件中，若文件不存在，创建后输入，若文件存在会将在原有的文件内容后追加内容
     * @param filePath
     * @param content
     */
    public static void appendWriteContent(String filePath,String content){
        try {
            FileWriter fw = new FileWriter(filePath, true);
            fw.write(content);
            fw.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 读取文件中数据
     * @param filePath  若不用绝对路径，直接写文件是与src目录同级
     * @return
     */
    public static List<String> readContent(String filePath){
        List<String> dataList = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(filePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                dataList.add(line);
            }
            bufferedReader.close();
            fis.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return dataList;
    }

}
